package dfferber.xstream;

/*
 * Copyright (C) 2005 Joe Walnes.
 * Copyright (C) 2006, 2007, 2008 XStream Committers.
 * All rights reserved.
 *
 * The software in this package is published under the terms of the BSD
 * style license a copy of which has been included with this distribution in
 * the LICENSE.txt file.
 * 
 * Created on 09. April 2005 by Joe Walnes
 */

import com.thoughtworks.xstream.alias.ClassMapper;
import com.thoughtworks.xstream.core.util.FastField;
import com.thoughtworks.xstream.mapper.Mapper;
import com.thoughtworks.xstream.mapper.MapperWrapper;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * Mapper that allows a field of a specific class to be replaced with a shorter
 * alias, or omitted entirely.
 * 
 * @author Joe Walnes
 */
public class PropertyAliasingMapper extends MapperWrapper {

	protected final Map<FastField, String> propertyToAliasMap = new HashMap<FastField, String>();
	protected final Map<FastField, String> aliasToPropertyMap = new HashMap<FastField, String>();
	protected final Set<FastField> propertiesToOmit = new HashSet<FastField>();

	public PropertyAliasingMapper(Mapper wrapped) {
		super(wrapped);
	}

	public void addPropertyAlias(String alias, Class<?> type, String propertyName) {
		propertyToAliasMap.put(key(type, propertyName), alias);
		aliasToPropertyMap.put(key(type, alias), propertyName);
	}

   public void addOmittedProperty(Class definedIn, String fieldName) {
      propertiesToOmit.add(key(definedIn, fieldName));
  }

	private FastField key(Class<?> type, String name) {
		return new FastField(type, name);
	}

	public String serializedMember(Class type, String memberName) {
		String alias = getMember(type, memberName, propertyToAliasMap);
		if (alias != null)
			return alias;
		return super.serializedMember(type, memberName);
	}

	public String realMember(Class type, String serialized) {
		String real = getMember(type, serialized, aliasToPropertyMap);
		if (real != null)
			return real;
		return super.realMember(type, serialized);
	}

    private String getMember(Class<?> type, String name, Map<FastField, String> map) {
        String member = null;
        for (Class<?> declaringType = type; member == null && declaringType != Object.class; declaringType = declaringType.getSuperclass()) {
            member = (String) map.get(key(declaringType, name));
        }
        return member;
    }

    public boolean shouldSerializeMember(Class definedIn, String fieldName) {
        return ! propertiesToOmit.contains(key(definedIn, fieldName));
    }

}
